# -*- coding: utf-8 -*-

from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.core.paginator import ObjectPaginator, InvalidPage
from blogpy.blog.models import Post,Category,Link,Comment,Tag,Widget,Widget_Model
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from time import strptime, strftime
from django import template
import datetime
import calendar,time
from blogpy.blog.widget import *
from django.newforms import widgets
from django.conf import settings

def index(request,page=0,latest_post_list=[]):
    commet_count = []
    time_arr = []
    prepage = False
    nextpage = False
    ispage = False
    if len(latest_post_list) == 0:
        paginator = ObjectPaginator(Post.objects.all().order_by('-pubdate'), 10)
        latest_post_list = paginator.get_page(page)
        page = int(page)
        if paginator.has_previous_page(page):
            prepage = True
            pnum = page-1
        if paginator.has_next_page(page):
            nextpage = True
            nnum = page+1
        if prepage or nextpage:
            ispage = True
    commet_count = getTime_arr(latest_post_list)
    time_arr = getCommet_count(latest_post_list)    
    list_post = zip(latest_post_list,time_arr,commet_count)
    wideget = creatWidget()
    index_dic = {
                'commet_count':commet_count,
                'time_arr':time_arr,
                'list_post':list_post,
                'prepage':prepage,
                'nextpage':nextpage,
                'ispage':ispage,
                'user':request.user
                }
    index_dic.update(wideget)
    return render_to_response('index.html', index_dic)

def getCatalog(request,catalogid):
    cataloglist = Post.objects.filter(catalog=catalogid)   
    return index(request,0,cataloglist)

def getTag(request,tagid):
	try:
	    tags = Tag.objects.get(id=tagid)
	    return index(request,0,tags.posts.all())
	except:
		return index(request)

def post(request, post_id):
    blog_post = get_object_or_404(Post, id=post_id)
    blog_post_next = list(Post.objects.filter(id__gt = post_id))[0:1]
    blog_post_previous = list(Post.objects.filter(id__lt = post_id))[-1:]
    time = monthtoEmonth(blog_post.pubdate)
    blog_comment = blog_post.comment_set.all().order_by('-comment_time')
    comment_count = len(blog_comment)
    wideget = creatWidget()
    index_dic = {
                'blog_post':blog_post,
                'blog_post_next':blog_post_next,
                'blog_post_previous':blog_post_previous,
                'time':time,
                'blog_comment':blog_comment,
                'comment_count':comment_count,
                'user':request.user,
                }
    index_dic.update(wideget)
    return render_to_response('blog_post.html',index_dic)

def recomment(request):
    import re
    val_dic = {
                'author':'\S',
                'email':'\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*',
                'url':'^[a-zA-z]+://(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$',
                'body':'\S',
                'submit':'\S',
                'postid':'\d+',
              }
    key_dic = {
                'author':'Name错误',
                'email':'Email错误',
                'url':'WebSite错误',
                'body':'评论内容不能为空',
                'submit':'错误',
            }
    for key,value in request.POST.items():
        if key == 'url' and value == 'http://':
            value = 'http://www.sina.com.cn'
        pa = val_dic.get(key)
        r = re.compile(pa)
        val = r.match(value)
        if val == None:
            return HttpResponse('<script>alert('"'%s'"');history.go(-1);</script>'%key_dic.get(key))
    author = request.POST['author']
    email = request.POST['email']
    url = request.POST['url']
    body = request.POST['body']
    postid = request.POST['postid']
    rec = Comment()
    rec.post = get_object_or_404(Post, id=postid)
    rec.comment_author = author
    rec.comment_email = email
    rec.comment_url = url
    rec.comment_content = body
    rec.save()
    return HttpResponseRedirect('/blog/%s/'%postid)

def archives(request,year,month):
    from calendar import monthrange as transforMon
    commet_count = []
    time_arr = []    
    year = int(year)
    month = int(month)
    latest_post_list = Post.objects.all().exclude(
                    pubdate__gte=datetime.datetime(year,month,transforMon(year,month)[1])).filter(
                    pubdate__gte=datetime.datetime(year,month,1))    
    return index(request,0,latest_post_list)

def monthtoEmonth(date = datetime.date.today()):
    month_dic = {
                '1':'Jan',
                '2':'Feb',
                '3':'Mar',
                '4':'Apr',
                '5':'May',
                '6':'Jun',
                '7':'Jul',
                '8':'Aug',
                '9':'Sep',
                '10':'Oct',
                '11':'Nov',
                '12':'Dec',
                }
    t = strptime(str(date)[0:10], '%Y-%m-%d')
    return month_dic.get(str(t[1])),t[2]

def getTime_arr(latest_post_list):
    return [llist.comment_set.all().count() for llist  in latest_post_list]

def getCommet_count(latest_post_list):
    return [monthtoEmonth(post.pubdate) for post in latest_post_list]
